import { Form, Drawer, Input, Select, Upload, Button, message, Icon, Tooltip } from 'antd';
import React from 'react';
import { connect } from 'dva';
import { postTicketAdd, postTicketEdit, postProcessDefinitionList } from '@/services/geographic';
import UserSession from "@/UserSession";
import axios from 'axios';
import http from '@/utils/http';

class EditTicket extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			visible: false,
			imgUrl: '',
			imgName: '',
			detail: null,
			id: null,
			isImgOk: true,
			userList: [],
			applicationId: null,
			userDataInfo: null,
		}
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this)
		}
	}

	initOpen = (row, applicationId) => {
		this.setState({ visible: true, detail: row, applicationId }, () => {
			if (row) {
				this.getEntryDetail(row);
			};
			this.getUserList();
		})
	}

	/* 获取详情 */
	getEntryDetail = async (res) => {
		this.props.form.setFieldsValue({
			name: res.name,
			imgUrl: res.imagePath,
			userFlowModuleKey: res.userFlowModuleKey,
		})
		this.setState({
			imgUrl: res.imagePath,
			imgName: res.imgName,
			userDataInfo: {
				key: res.userFlowModuleKey,
				templateVersionId: res.orderModuleId,
			}
		});
	}

	/** 用户流程模型 */
	getUserList = async () => {
		const { currentUser } = this.props;
		const res = await postProcessDefinitionList({
			tenantId: currentUser.kfTenantId,
			createChannel: 'customer',
		});
		// console.log(res);
		this.setState({ userList: res });
	}

	/* 上传图片之前 */
	beforeUpload = file => {
		const b = /\.(png|jpg|jpeg|gif|bmp|tif|ico|webp)$/;
		const a = file.name.toLowerCase();

		const pig = b.test(a);
		const isJPG = file.type;
		const isLt2M = file.size / 1024 / 1024 < 2;

		if (!pig) {
			if (!isLt2M) {
				message.error('请上传小于2M的图片');
			} else {
				message.error('请上传图片格式');
			}
		} else if (!isLt2M) {
			message.error('请上传小于2M的图片');
		}
		return isJPG && isLt2M && pig;
	};

	/* 修改上传图片 */
	handleChangeImage = info => {
		if (info.file.status === 'done') {
			this.setState({
				imgUrl: info.file.response.url ? info.file.response.url : '',
				imgName: info.file.response.original ? info.file.response.original : '',
				isImgOk: true,
			})
		}
	}

	/* 关闭弹窗 */
	cancelModal = () => {
		this.props.form.resetFields();
		this.setState({
			visible: false,
			imgUrl: '',
			imgName: '',
			detail: null,
			isImgOk: true,
		})
	}

	/* 保存/编辑标签基础信息前校验 */
	doSubmitForm = () => {
		const that = this;
		const { imgUrl, imgName, id, applicationId, userDataInfo } = that.state;
		that.props.form.validateFields((errors, values) => {
			if (!errors) {
				if (!imgUrl) {
					that.setState({
						isImgOk: false
					})
					return false
				}
				const userTypeIdList = values.userType ? values.userType : [];
				const obj = {
					applicationId,
					name: values.name,
					imagePath: imgUrl,
					imgName,
					userFlowModuleKey: userDataInfo?.key,
					orderModuleId: userDataInfo?.templateVersionId,
				};
				that.doSubmitFetch(obj)
			}
		})
	}

	/* 新增/编辑 请求接口 */
	doSubmitFetch = async (obj) => {
		const that = this;
		const { detail } = that.state;
		let res = {};
		if (detail) {
			obj.id = detail.id;
			res = await postTicketEdit(obj)
		} else {
			res = await postTicketAdd(obj);
		};
		message.info(res.msg);
		that.cancelModal();
		that.props.getTicketList();
	}

	userFlowModuleChange = (value, e) => {
		this.setState({ userDataInfo: e.props.data });
	}

	render() {
		const { getFieldDecorator } = this.props.form;
		const { robotId } = this.props;
		const { visible, imgUrl, isImgOk, userList } = this.state;
		const formItemLayout = {
			labelCol: {
				xs: { span: 24 },
				sm: { span: 5 },
			},
			wrapperCol: {
				xs: { span: 24 },
				sm: { span: 19 },
			},
		};
		const renderLabel = (label, tip) => {
			return (
				<label>
					{label}
					<Tooltip placement="topLeft" title={tip}>
						<Icon type="question-circle" style={{ verticalAlign: 'baseline', margin: '0 5px' }} />
					</Tooltip>
				</label>
			)
		}

		return (
			<div>
				<Drawer
					title="工单配置添加/编辑"
					visible={visible}
					width={650}
					onClose={this.cancelModal}
				>
					<Form {...formItemLayout}>
						<Form.Item label="工单名称">
							{getFieldDecorator('name', {
								rules: [{ required: true, message: '工单名称' }]
							})(<Input />)}
						</Form.Item>
						<Form.Item label="图片">
							{getFieldDecorator('imgUrl', {
								rules: [{ required: true, message: '请上传图片' }]
							})(
								<Upload
									name="file"
									listType="picture"
									className="avatar-uploader"
									showUploadList={false}
									action="/cloud/file/upload"
									beforeUpload={this.beforeUpload}
									onChange={this.handleChangeImage}
									accept=".png,.jpg,.jpeg,.gif,.bmp,.tif,.ico,.webp"
								>
									{imgUrl ? <img src={imgUrl} style={{ width: 50, height: 50, marginRight: 10 }} /> : ''}
									<Button>{imgUrl ? '重新上传' : '上传图片'}</Button>
								</Upload>
								)}
							{isImgOk ? '' : <div className="ant-form-explain" style={{ color: '#f5222d' }}>请上传图片</div>}
						</Form.Item>
						<Form.Item label={renderLabel('用户流程模型', '用户流程模型对应工单模板，在客服系统中配置')}>
							{getFieldDecorator('userFlowModuleKey', {
								// rules: [{ required: true, message: '请选择用户类型' }]
							})(
								<Select onSelect={(value, e) => this.userFlowModuleChange(value, e)}>
									{userList.map((item, index) => {
										return <Select.Option value={item.key} key={item.key} data={item}>{item.name}</Select.Option>
									})}
								</Select>
							)}
						</Form.Item>
					</Form>

					<div
						style={{
							position: 'absolute',
							right: 0,
							bottom: 0,
							width: '100%',
							borderTop: '1px solid #e9e9e9',
							padding: '10px 16px',
							background: '#fff',
							textAlign: 'right',
						}}
					>
						<Button onClick={this.cancelModal} style={{ marginRight: 8 }}>取消</Button>
						<Button onClick={this.doSubmitForm} type="primary">确定</Button>
					</div>
				</Drawer>

			</div>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(EditTicket))
